<?php
namespace app\index\controller;

use app\common\model\DrawRecord;
use app\common\model\DrawTime;
use app\common\model\Exchange;
use app\common\model\Product as ProductModel;
use app\common\model\ProductPiece as ProductPieceModel;
use app\common\model\UserProductPiece;
use app\lib\exception\BaseException;
use EasyWeChat\Factory;
use think\Db;

class Product extends BaseController
{
    public $product_id;

    public function __construct()
    {
        parent::__construct();
        $this->product_id = input('product_id');
    }

    public function index()
    {
        //微信分享
        $config = [
            'app_id' => config('ofcl.app_id'),
            'secret' => config('ofcl.app_secret'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $this->assign('wx_config', $app->jssdk->buildConfig(array('onMenuShareTimeline', 'onMenuShareAppMessage'), false));

        //如果没有产品id，返回
        if (!$this->product_id) {
            throw new BaseException(['msg' => '没有指定商品！']);
        }
        //获取product信息
        $product = ProductModel::getById($this->product_id);
        //显示用户已拥有的产品拼图
        $pieces = UserProductPiece::getByUserId($this->user_info['id']);
        $pieces = collection($pieces)->toArray();
        $npieces = [];
        foreach ($pieces as $piece) {
            $npieces[$piece['piece_id']] = $piece;
        }
        $tempProduct = $product->toArray();
        foreach ($product['piece'] as $k => $v) {
            $tempProduct['piece'][$k]['number'] = isset($npieces[$v['id']]['number']) ? $npieces[$v['id']]['number'] : 0;
        }
        $this->assign('product', $tempProduct);
        //页面分享设置信息
        $share_info = model('page')->where('name="product"')->find();
        if (!$share_info) throw new BaseException(['无页面分享信息！']);
        $share_info = $share_info->toArray();
        if ($share_info['use_main_img']) {
            $share_info['img_url'] = $product['img_url'];
        }
        $this->assign('share_info', $share_info);
        //剩余次数
        $draw_time = DrawTime::getByUserId($this->user_info['id']);
        //检查时间是否跨日
        //如果跨日了，恢复次数
        $last_time_end = strtotime(date($draw_time['date'] . ' 23:59:59'));
        if ($last_time_end < time()) {//跨日了
            $draw_time->save(['remain_times' => config('common.daily_times')]);
        }
        $this->assign('remain_times',$draw_time->remain_times);
        return $this->fetch();

    }

    public function getAll()
    {
        $products = ProductModel::getAll();
        return successReturn($products);
    }

    public function draw()
    {
        if (!$this->product_id) {
            throw new BaseException(['msg' => '没有指定商品！']);
        }
        //检查次数有没有用完
        //如果当日已经抽过退出
        $model = new DrawTime();
        $draw_time = $model->getByUserId($this->user_info['id']);
        if ($draw_time->remain_times <= 0) throw new BaseException(['msg' => '今日抽奖机会已经用完']);

        //随机生成piece_id
        $pieces = ProductPieceModel::getByProductId($this->product_id, 'id');
        $pieces = collection($pieces)->toArray();
        $ids = [];
        foreach ($pieces as $piece) {
            $ids[] = $piece['id'];
        }

        $random_keys = array_rand($ids, 1);
        $piece_id = $ids[$random_keys];
        Db::startTrans();
        try {
            UserProductPiece::incUserPiece($this->user_info['id'], $this->product_id, $piece_id);
            //保存抽奖时间
            DrawTime::updateLastTime($this->user_info['id'], time());
            Db::commit();
            $piece = ProductPieceModel::getById($piece_id);
            //保存抽奖记录
            $record = [
                'user_id' => $this->user_info['id'],
                'piece_id' => $piece->id,
                'product_id' => $piece->product_id,
            ];
            DrawRecord::createOne($record);
            return successReturn($piece, '恭喜您！抽到一块碎片');
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }


    }

    public function exchange()
    {
        if (!$this->product_id) {
            throw new BaseException(['msg' => '没有指定商品！']);
        }
        $product = Db::table('__PRODUCT__')->where('id='.$this->product_id)->find();
        $time = time();
        if($product['end_time']<$time || $product['start_time']>$time)
            throw new BaseException(['msg'=>'非常抱歉，不在活动时间内！']);

        //先获取都有哪些碎片
        $piece_ids = ProductPieceModel::where('product_id=' . $this->product_id)->field('id')->select();
        $piece_ids = collection($piece_ids)->toArray();
        $piece_ids_arr = [];
        foreach ($piece_ids as $v) {
            $piece_ids_arr[] = $v['id'];
        }
        $piece_id_str = implode(',', $piece_ids_arr);
        //检查用户卡券是否齐全
        $where = 'user_id=' . $this->user_info['id'];
        $where .= ' AND piece_id in (' . $piece_id_str . ')';
        $user_pieces = UserProductPiece::field('id,number,piece_id')->where($where)->select();
        $user_pieces = collection($user_pieces)->toArray();
        if(!$user_pieces) throw new BaseException(['msg'=>'很抱歉，您还没有碎片！']);
        $temp = [];
        foreach ($user_pieces as $v){
            $temp[$v['piece_id']] = $v;
        }
        foreach ($piece_ids as $k=>$v) {
            if(empty($temp[$v['id']]['number'])) throw new BaseException(['msg' => '很抱歉！碎片不足']);
        }
        Db::startTrans();
        try {
            $pieces = UserProductPiece::
            where($where)->setDec('number');
            //生成兑奖数据
            $time = time();
            $product = Db::table('__PRODUCT__')->where('id=' . $this->product_id)->find();
            $data = [
                'user_id' => $this->user_info['id'],
                'product_id' => $this->product_id,
                'nickname' => $this->user_info['nickname'],
                'exchange_date' => date('Y-n-j', $time),
                'create_time' => $time,
                'cost' => $product['cost'],
                'start_time' => $product['start_time'],
                'end_time' => $product['end_time'],
            ];
            $res = Exchange::create($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
        return successReturn($product, '恭喜您！产品兑换成功！');
    }

    public function using()
    {
        return $this->fetch();
    }
    public function deleteOne(){
        $res = ProductModel::deleteOne(input('id'));
        return successReturn($res);
    }


}
